package com.ctyun.xstore.s3.api.object;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.HttpMethod;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.ctyun.xstore.s3.client.AmazonS3ClientBuilder;

import java.net.URL;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;


public class GeneratePresignedPutUrl {
    public static String generatePresignedPutUrl(String keyName, String bucketName, AmazonS3 s3Client) {
        LocalDateTime expirationDateTime = LocalDateTime.now().plusSeconds(5 * 60);//url的有效时间5分钟
        Date expiration = Date.from(expirationDateTime.atZone(ZoneId.systemDefault()).toInstant());
        if (s3Client == null) {
            s3Client = AmazonS3ClientBuilder.buildAmazonS3Client();
        }
        try {
            GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, keyName)
                    .withMethod(HttpMethod.PUT)
                    .withExpiration(expiration);
            //这里生成预签名地址可以不用设置header。 在发送请求的时候在请求头携带上x-amz-grant-read即可
            //generatePresignedUrlRequest.putCustomRequestHeader(Permission.Read.getHeaderName(), GroupGrantee.AllUsers.getTypeIdentifier() + "=\"" + GroupGrantee.AllUsers.getIdentifier() + "\"");
            URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
            return url.toString();
        } catch (AmazonServiceException e) {
            System.err.println(e.getErrorMessage());
        }
        System.out.println("Done");
        return null;
    }

    public static String generatePresignedPutUrl(String keyName, String bucketName) {
        return generatePresignedPutUrl(keyName, bucketName, null);
    }
}

